from pprint import pprint

from django.shortcuts import render
from django import http
from django.views import View
from meiduo_mall.utils.response_code import RETCODE
from orders.models import OrderInfo, OrderGoods
from alipay import AliPay
from .models import Payment
from django.conf import settings
from meiduo_mall.utils.log import logger_out
import os


class PaymentView (View):
    def get(self, request, order_id):
        try:
            order = OrderInfo.objects.get(pk=order_id)
        except Exception as e:
            logger_out.warning(e)
            return http.Http404('订单无效')
        # 生成一个url地址
        alipay = AliPay(
            appid=settings.ALIPAY_APPID,
            app_notify_url=None,
            app_private_key_path=os.path.join(settings.BASE_DIR, 'libs/alipay/app_private_key.pem'),
            alipay_public_key_path=os.path.join(settings.BASE_DIR, 'libs/alipay/app_public_key.pem'),
            sign_type="RSA2",
            debug=settings.ALIPAY_DEBUG,
        )
        # # 生成支付的参数
        order_string = alipay.api_alipay_trade_page_pay(
            out_trade_no=order_id,
            total_amount=str(order.total_amount),
            subject='美多商城在线支付',
            return_url=settings.ALIPAY_RETURN_URL,
        )
        # 拼接一个返回的支付地址
        alipay_url = settings.ALIPAY_URL + "?" + order_string
        # 响应
        return http.JsonResponse({
            'code': RETCODE.OK,
            'errmsg': 'ok',
            'alipay_url': alipay_url,
        })


class PayStatusView (View):
    def get(self, request):
        # 获取接受到的数据转化为字典
        data = request.GET.dict()
        pprint(data)
        """
        获取数据的格式
        {'version': '1.0',
        'charset': 'utf- 8',
        'total_amount': '3398.00',
        'sign_type': 'RSA2',
        'sign': 'IdnvbeuvfArwvaD2RvCP3pih0N KYgSvUPgWza8FM8SsAnTgCxokC1YKwT/2nFHrL9M7OItpoVt+
                O2070jCEx1FbBdQwol9sV7FpTqFvE02Iu7PNmKuxrEa5WZUoq7EWGqDnjGY +sF8QyLgfXOwq4mns +
                IiOFZfrsdw76yJC55ToHuVWkx41/qCDV1hugNAIyTu7YnjynwSeueKB3p8Q6NaZIqRxBnHl5BUbfV1hAXyLtJfVxZHhi2buEsVxuZd5r
                GWX7tIvs7wFbo0tY7% 2FHFU3af7fgRJRHxVDshImTOQNr6OYr3dWP2ioZjgnIvIeD+1s9wrbBbcEmvDO8eb9QLZQ= =',
        'timestamp': '2019-06-10 12:21:42',
        'selle r_id': '2088102177847625',
        'method': 'alipay.trade.page.pay.return',
        'out_trade_no': '20190610122240000000036',
        'app_id': '2016092900626065',
        'auth_app_id': '2016092900626065',
        'trade_no': '2019061022001439141000012032'}
        """
        trade_no = data.get('trade_no')
        out_trade_no = data.get('out_trade_no')
        sign = data.pop('sign')
        # 验证是否交易成功！
        alipay = AliPay(
            appid=settings.ALIPAY_APPID,
            app_notify_url=None,
            app_private_key_path=os.path.join (settings.BASE_DIR, 'libs/alipay/app_private_key.pem'),
            alipay_public_key_path=os.path.join (settings.BASE_DIR, 'libs/alipay/app_public_key.pem'),
            sign_type="RSA2",
            debug=settings.ALIPAY_DEBUG,
        )
        # 验证是否付款ok
        success = alipay.verify(data, sign)
        if not success:
            return http.HttpResponseBadRequest('支付失败！请重新支付')

        # 处理
        try:
            # 更改付款的状态
            order = OrderInfo.objects.filter(order_id=out_trade_no).update(status=4)
            # 创建用户付款订单
            pay = Payment.objects.create(order_id=out_trade_no, trade_id=trade_no)

        except Exception as e:
            logger_out.warning(e)
            return render(request, 'user_center_order.html')
            # return http.HttpResponseBadRequest('数据库保存失败！请联系客户人员！')
        context = {
            'trade_no': trade_no,
        }
        # 响应
        return render(request, 'pay_success.html', context)
